package com.hsingh.eclipse.mercury.extension.command;

import java.util.Collections;

import org.eclipse.core.commands.Command;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.common.NotDefinedException;
import org.eclipse.core.expressions.IEvaluationContext;
import org.eclipse.swt.widgets.Event;
import org.eclipse.ui.PlatformUI;

import com.hsingh.eclipse.mercury.extensionpoint.definition.AbstractTask;
import com.hsingh.eclipse.mercury.extensionpoint.definition.ITask;

public class CommandTask extends AbstractTask implements ITask {

  private final Command cmd;

  public CommandTask(Command cmd) {
    this.cmd = cmd;
  }

  @Override
  public String getName() {
    String name = "";
    try {
      name = cmd.getName();
    } catch (NotDefinedException e) {
      name = "Unknown";
    }

    return name;
  }

  @Override
  public String getLabel() {
    return getName() + " - " + getCategory();
  }

  private String getCategory() {
    try {
      return cmd.getCategory().getName();
    } catch (NotDefinedException e) {
      return "Unknown";
    }
  }

  @Override
  public String getDetailsLabel() {
    String detailsLabel = "";
    try {
      detailsLabel = cmd.getDescription();
    } catch (NotDefinedException e) {}

    if ("".equals(detailsLabel) || detailsLabel == null) {
      detailsLabel = getName();
    }
    return detailsLabel;
  }

  @Override
  public Object getItem() {
    return cmd;
  }

  @Override
  public void execute(ExecutionEvent event) {
    try {
      IEvaluationContext applicationContext = (IEvaluationContext) event.getApplicationContext();
      applicationContext.addVariable("activeWorkbenchWindow", PlatformUI.getWorkbench().getActiveWorkbenchWindow());

      ExecutionEvent e = new ExecutionEvent(cmd, Collections.EMPTY_MAP, new Event(), applicationContext);
      cmd.executeWithChecks(e);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
